using UnityEngine;
using System;

public class Note : MonoBehaviour
{
    [Header("音符设置")]
    [SerializeField] private float speed = 5f;
    [SerializeField] private int scoreValue = 100;
    [SerializeField] private NoteType noteType = NoteType.Normal;
    
    [Header("视觉效果")]
    [SerializeField] private GameObject hitEffect;
    [SerializeField] private GameObject missEffect;
    
    // 音符类型枚举
    public enum NoteType { High, Mid, Low, Special }
    
    // 事件
    public static event Action<int, bool> OnNoteHit; // 分数, 是否完美击中
    public static event Action OnNoteMissed;
    
    private bool isHit = false;
    private GameManager gameManager;
    
    private void Start()
    {
        gameManager = FindObjectOfType<GameManager>();
    }
    
    private void Update()
    {
        // 音符从右向左移动
        transform.Translate(Vector3.left * speed * Time.deltaTime);
        
        // 如果音符移出屏幕且未被击中，则视为错过
        if (transform.position.x < -10f && !isHit)
        {
            OnMissed();
        }
    }
    
    // 当音符被击中时调用
    public void OnHit(bool correctAttack)
    {
        if (isHit) return; // 防止重复计分
        
        isHit = true;
        
        if (correctAttack)
        {
            // 播放命中特效
            if (hitEffect != null)
            {
                Instantiate(hitEffect, transform.position, Quaternion.identity);
            }
            
            // 触发命中事件，传递分数
            OnNoteHit?.Invoke(scoreValue, true);
            
            // 播放音效（可以在GameManager中实现）
            if (gameManager != null)
            {
                gameManager.PlayHitSound();
            }
        }
        else
        {
            // 错误的攻击类型
            if (missEffect != null)
            {
                Instantiate(missEffect, transform.position, Quaternion.identity);
            }
            
            // 触发命中事件，但分数较低
            OnNoteHit?.Invoke(scoreValue / 2, false);
        }
        
        // 销毁音符
        Destroy(gameObject);
    }
    
    // 当音符被错过时调用
    private void OnMissed()
    {
        if (isHit) return;
        
        isHit = true;
        
        // 触发错过事件
        OnNoteMissed?.Invoke();
        
        // 播放错过特效
        if (missEffect != null)
        {
            Instantiate(missEffect, transform.position, Quaternion.identity);
        }
        
        // 销毁音符
        Destroy(gameObject);
    }
    
    // 获取音符类型
    public NoteType GetNoteType()
    {
        return noteType;
    }
}